package ecnu.ecgbackend.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ecnu.ecgbackend.entity.User;
import ecnu.ecgbackend.service.DiagnosisAiDiagnosisService;
import ecnu.ecgbackend.service.DiagnosisUserService;
import ecnu.ecgbackend.utils.ResponseObject;
import ecnu.ecgbackend.utils.Result;
import ecnu.ecgbackend.utils.StatusObject;
import ecnu.ecgbackend.utils.TaskObject;
import javafx.scene.control.TableView;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/diagnosis")
public class DiagnosisAiDiagnosisController {
    @Resource
    DiagnosisAiDiagnosisService diagnosisAiDiagnosisService;
    @Resource
    DiagnosisUserService diagnosisUserService;


    @PostMapping("/static")
    public Result addStaticDiagnosis(String fileName){
        try{
            if(!diagnosisAiDiagnosisService.isIntegralEnough()){
                return Result.error().message("积分不充足，请联系管理员充值!");
            }
            User user= (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            Map<String,Object> result=new HashMap<>();
            String rawDataId=user.getId()+"_"+fileName;
            ResponseObject responseObject= diagnosisAiDiagnosisService.saveStaticDiagnosis(fileName);
            if(responseObject.getCode()==0){
                Map<String,Object> updateIntegral= diagnosisUserService.minusIntegral();
                ObjectMapper objectMapper=new ObjectMapper();
                String report=objectMapper.writeValueAsString(responseObject.getData());
                diagnosisAiDiagnosisService.editStaticRawDataStatus("report",rawDataId,report);
                boolean success=(Boolean) updateIntegral.get("success");
                result.put("data",responseObject.getData());
                if(success){
                    result.put("integral",updateIntegral.get("integral"));
                }
                return Result.ok(result).message("AI诊断成功！");
            }
            diagnosisAiDiagnosisService.editStaticRawDataStatus("error",rawDataId,null);
            return Result.error().message("AI诊断失败");
        }catch (IOException e){
            return Result.error().code(500).message(e.getMessage());
        }
    }

    @PostMapping("/dynamic")
    public Result addDynamicDiagnosis(String fileName) {
        try{
            if(!diagnosisAiDiagnosisService.isIntegralEnough()){
                return Result.error().message("积分不充足，请联系管理员充值!");
            }
            User user= (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            Map<String,Object> result=new HashMap<>();
            String rawDataId=user.getId()+"_"+fileName;
            TaskObject response=diagnosisAiDiagnosisService.saveDynamicDiagnosis(fileName);
            if(response!=null){
                Map<String,Object> updateIntegral= diagnosisUserService.minusIntegral();
                diagnosisAiDiagnosisService.editStaticRawDataStatus("queue",rawDataId,response.getTask_id());
                boolean success=(Boolean) updateIntegral.get("success");
                result.put("data",response);
                if(success){
                    result.put("integral",updateIntegral.get("integral"));
                }
                return Result.ok(result).message("AI诊断成功，正在分析中！");
            }
            diagnosisAiDiagnosisService.editStaticRawDataStatus("error",rawDataId,null);
            return Result.error().message("AI诊断失败");
        }catch (IOException e){
            return Result.error().code(500).message(e.getMessage());
        }
    }
    @GetMapping("/dynamic/status")
    public Result queryDynamicStatus(@RequestParam(name = "taskId") String taskId) {
        try{
            StatusObject result= diagnosisAiDiagnosisService.getDynamicStatus(taskId);
            return Result.ok(result);
        }catch (IOException e){
            return Result.error().code(500).message(e.getMessage());
        }

    }
    @GetMapping("/history")
    public Result getHistoryService(@RequestParam("category") String category,
                                    @RequestParam("pageNum") int pageNum,
                                    @RequestParam("pageSize") int pageSize) {
        try{
            return Result.ok(diagnosisAiDiagnosisService.getHistoryService(category,pageNum,pageSize));
        }catch (IOException e) {
            return Result.error().code(500).message(e.getMessage());
        }
    }
    @GetMapping("/dynamic/result")
    public Result queryDynamicResult(@RequestParam(name = "rawDataId")String rawDataId){
        try{
            Map<String,Object> result=diagnosisAiDiagnosisService.getDynamicResult(rawDataId);
            return Result.ok(result);
        }catch (IOException e) {
            return Result.error().code(500).message(e.getMessage());
        }
    }
    @GetMapping("/static/result")
    public Result queryStaticResult(@RequestParam(name="rawDataId")String rawDataId){
        return Result.ok(diagnosisAiDiagnosisService.getStaticResult(rawDataId));
    }
    @PostMapping("/report")
    public Result modifyArtificialDiagnosisReport(String rawDataId,String patientId,String report){
        if(diagnosisAiDiagnosisService.editArtificialDiagnosisReport(rawDataId,patientId,report)){
            return Result.ok().message("诊断意见提交成功！");
        }
        return Result.error().message("诊断意见提交失败");
    }


}
